package com.css.dzj.zfjg.modules.detail.controller;

import com.alibaba.fastjson.JSON;
import com.css.dzj.zfjg.common.audit.service.SysAuditService;
import com.css.dzj.zfjg.common.util.Constant;
import com.css.dzj.zfjg.common.util.PlatformFileUtil;
import com.css.dzj.zfjg.common.util.R;
import com.css.dzj.zfjg.common.util.ServiceUtil;
import com.css.dzj.zfjg.modules.clue.entity.Clue;
import com.css.dzj.zfjg.modules.clue.service.ClueService;
import com.css.dzj.zfjg.modules.detail.entity.CreditPushInfo;
import com.css.dzj.zfjg.modules.detail.entity.Detail;
import com.css.dzj.zfjg.modules.detail.service.DetailService;
import com.css.dzj.zfjg.modules.detail.vo.Infopush;
import com.css.dzj.zfjg.common.util.page.PageBean;
import com.querydsl.core.QueryResults;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;

/**
 * 信用详情
 * @author liyuan
 */
@RestController
@RequestMapping("/detail")
public class DetailController {
    @Autowired
    private DetailService detailService;

    // base日志接口
    @Autowired
    SysAuditService sysAuditService;
    @Autowired
    HttpServletRequest request;

    @Autowired
    private ClueService clueService;

    @Autowired
    private PlatformFileUtil platformFileUtil;

    /**
     * 多条件分页查询
     *
     * @param enterpriseName
     * @param enterpriseClassification
     * @param enterpriseScoreBegin
     * @param enterpriseScoreEnd
     * @param status
     * @param pageSize
     * @param pageNo
     * @return
     */
    @GetMapping("/getPage")
    public R getPage(@RequestParam(required = false) String enterpriseName,
                     @RequestParam(required = false) String enterpriseClassification,
                     @RequestParam(required = false) String enterpriseScoreBegin,
                     @RequestParam(required = false) String enterpriseScoreEnd,
                     @RequestParam(required = false) String status,
                     @RequestParam Integer pageSize, @RequestParam Integer pageNo) {
        String s = "";
        try {
            PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
            QueryResults<Detail> page = detailService.getPage(enterpriseName.trim(), enterpriseClassification, enterpriseScoreBegin.trim(), enterpriseScoreEnd.trim(), status, pageRequest);
            s = JSON.toJSONString(page);
            return R.ok().put("data", page);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 单个新增
     *
     * @param detail
     * @return
     */
    @PostMapping("/add")
    public R addDetail(@RequestBody Detail detail) {
        String s = "";
        try {
            detailService.add(detail);
            s = JSON.toJSONString(detail);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 修改
     *
     * @param detail
     * @return
     */
    @PostMapping("/update")
    public R updateDetail(@RequestBody Detail detail) {
        String s = "";
        try {
            detailService.update(detail);
            s = JSON.toJSONString(detail);
            sysAuditService.saveSuccessAudit("企业信用信息修改成功", Constant.ZFJG_DETAIL, Constant.PT, Constant.ZFJG_UPDATE, s, request);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            s = JSON.toJSONString(detail);
            sysAuditService.saveFailAudit("企业信用信息修改失败", Constant.ZFJG_DETAIL, Constant.YZ, Constant.ZFJG_UPDATE, s, e, request);
            return R.error(e.getMessage());
        }
    }

    /**
     * 模板下载
     * 用不着
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("excelModel")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        InputStream inputStream = new FileInputStream(new File(ResourceUtils.getURL("classpath:").getPath() + "/template.xls"));
        byte[] buffer = IOUtils.toByteArray(inputStream);
        response.setContentType("application/template.xls;" + "charset = UTF-8");
        String name = "模板";
        name = new String(name.getBytes(), "ISO-8859-1");
        response.setHeader("Content-Disposition", "attachment; filename=" + name + "..xls");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        String s ="";
        sysAuditService.saveSuccessAudit("企业信用信息模板下载成功", Constant.ZFJG_DETAIL, Constant.PT, Constant.ZFJG_EXCELMODEL, s, request);
    }

    /**
     * 从Excel表格中批量导入数据到数据库
     * 信用详情批量导入
     *
     * @param file
     * @return
     */
    @PostMapping("/import")
    public R addDetailFormExcel(@RequestParam("file") MultipartFile file) {
        String s = "";
        try {
            detailService.addDetailFromExcel(file);
            s = JSON.toJSONString("");
            sysAuditService.saveSuccessAudit("企业信用信息导入成功", Constant.ZFJG_DETAIL, Constant.PT, Constant.ZFJG_DEPTEXCEL, s, request);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            sysAuditService.saveFailAudit("企业信用信息导入失败", Constant.ZFJG_DETAIL, Constant.YZ, Constant.ZFJG_DEPTEXCEL, s, e, request);
            return R.error(e.getMessage());
        }
    }

    /**
     * 从Excel表格中批量导入数据到应急部对应系统
     * 结果反馈: 地震局对企业执法完成后，维护企业监管结果，并将信用监管结果返回至应急部对应系统中。
     *
     * @param file
     * @return
     * @athor liyuan
     */
    @PostMapping("/importToRemote")
    public R importToRemote(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        String s = "";
        try {
            // 接口待应急部对应系统提供
            //detailService.addDetailFromExcel(file);
            detailService.importToRemote(file, request);
            sysAuditService.saveSuccessAudit("从excel表格中批量导入企业信用信息到应急部系统成功", Constant.ZFJG_DETAIL, Constant.PT, Constant.ZFJG_DEPTEXCEL, s, request);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            sysAuditService.saveFailAudit("从excel表格中批量导入企业信用信息到应急部系统失败", Constant.ZFJG_DETAIL, Constant.YZ, Constant.ZFJG_DEPTEXCEL, s, e, request);
            return R.error(e.getMessage());
        }
    }

    /**
     * 导出
     * 导出选中行数据，待定
     *
     * @param response
     * @param ids
     * @return
     */
    @GetMapping("/exportByIds")
    public R exportDetailToExcel(HttpServletResponse response, @RequestParam String ids) {
        String s ="";
        try {
            List<Detail> details = detailService.queryByIds(ids);
            detailService.exportDetailToExcel(response, details);
            s = JSON.toJSONString(details);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 根据参数导出数据到Excel
     * @param response
     * @param enterpriseName
     * @param enterpriseClassification
     * @param enterpriseScoreBegin
     * @param enterpriseScoreEnd
     * @param status
     * @return
     */
    @GetMapping("/export")
    public R export(HttpServletResponse response,
                    @RequestParam(required = false) String enterpriseName,
                    @RequestParam(required = false) String enterpriseClassification,
                    @RequestParam(required = false) String enterpriseScoreBegin,
                    @RequestParam(required = false) String enterpriseScoreEnd,
                    @RequestParam(required = false) String status) {
        String s = "";
        try {
            List<Detail> details = detailService.queryByParams(enterpriseName.trim(),enterpriseClassification,
                    enterpriseScoreBegin.trim(),enterpriseScoreEnd.trim(),status);
            detailService.exportDetailToExcel(response, details);
            s = JSON.toJSONString(details);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }

    /**
     * 通过ID查询
     *
     * @param id
     * @return
     */
    @GetMapping("/findById")
    public R findDetailById(@RequestParam String id) {
        String s = "";
        try {
            Detail detail = detailService.findById(id);
            s = JSON.toJSONString(id);
            return R.ok().put("data", detail);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }


    /**
     * 根据企业证件号码修改状态为已调整
     * @param enterpriseIdNumber
     * @returna
     */
    @PostMapping("/updateStatus")
    public R updateStatus(@RequestParam String enterpriseIdNumber) {
        String s = "";
        try {
            if(StringUtils.isEmpty(enterpriseIdNumber)) {
                return R.error("企业证件号码不能为空");
            }
            Detail detail = detailService.queryByIdNumber(enterpriseIdNumber);
            if(detail == null) {
                return R.error("该企业的信用评估结果明细不存在");
            }
            detail.setStatus(Constant.ADJUSTED);
            detailService.update(detail);
            s = JSON.toJSONString(detail);
            sysAuditService.saveSuccessAudit("根据企业证件号码修改企业信用信息状态为已调整成功", Constant.ZFJG_DETAIL, Constant.PT, Constant.ZFJG_UPDATE, s, request);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            sysAuditService.saveFailAudit("根据企业证件号码修改企业信用信息状态为已调整失败", Constant.ZFJG_DETAIL, Constant.YZ, Constant.ZFJG_UPDATE, s, e, request);
            return R.error(e.getMessage());
        }
    }

    /**
     * 反馈
     * @param id
     * @return
     */
    @PostMapping("/dffeedback")
    public R feedback(@RequestParam String id, HttpServletRequest request) {
        String s = "";
        try {
            if(StringUtils.isEmpty(id)) {
                return R.error("企业信用id不能为空");
            }
            Detail detail = detailService.findById(id);
            if(detail == null) {
                return R.error("企业信用详情不存在");
            }
            detail.setStatus(Constant.FEEDBACK);
            detail.setFeedbackPerson(ServiceUtil.getLoginName(request));
            detail.setFeedbackOrg(ServiceUtil.getOrgName(request));
            detail.setFeedbackTime(new Date());
            if(StringUtils.isEmpty(detail.getEnterpriseIdNumber())) {
                return R.error("该企业信用的企业证件号码不存在");
            }
            Clue clue = clueService.queryByIdNumber(detail.getEnterpriseIdNumber());
            if(clue != null) {
                clue.setStatus(Constant.FEEDBACK);
            }
            // 反馈记录
            CreditPushInfo creditPushInfo = new CreditPushInfo();
            creditPushInfo.setEnterpriseIdNumber(detail.getEnterpriseIdNumber());
            creditPushInfo.setFeedbackOrg(detail.getFeedbackOrg());
            creditPushInfo.setFeedbackPerson(detail.getFeedbackPerson());
            creditPushInfo.setFeedbackTime(detail.getFeedbackTime());
            detailService.feedback(detail, clue, creditPushInfo);
            s = JSON.toJSONString(id);
            sysAuditService.saveSuccessAudit("企业信用信息反馈成功", Constant.ZFJG_DETAIL, Constant.PT, Constant.ZFJG_FEEDBACK, s, request);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            sysAuditService.saveFailAudit("企业信用信息反馈失败", Constant.ZFJG_DETAIL, Constant.YZ, Constant.ZFJG_FEEDBACK, s, e, request);
            return R.error(e.getMessage());
        }
    }

    @GetMapping("/getInfopush")
    public R getInfopush(@RequestParam Integer pageSize, @RequestParam Integer pageNo) {
        String s = "";
        try {
            PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
            PageBean<Infopush> page = detailService.groupBy(pageRequest);
            s = JSON.toJSONString(page);
            sysAuditService.saveSuccessAudit("获取信用分类信息推送信息成功", Constant.ZFJG_DETAIL, Constant.PT, Constant.ZFJG_PAGE, s, request);
            return R.ok().put("data", page);
        } catch (Exception e) {
            e.printStackTrace();
            sysAuditService.saveFailAudit("获取信用分类信息推送信息失败", Constant.ZFJG_DETAIL, Constant.YZ, Constant.ZFJG_PAGE, s, e, request);
            return R.error(e.getMessage());
        }
    }
    /**
     * 根据证件号码查询详情
     */
    @GetMapping("/queryById")
    public R queryById(@RequestParam String enterpriseIdNumber) {
        String s = "";
        try {
            Detail jgLhjgCreditAssessEntity = detailService.queryByIdNumber(enterpriseIdNumber);
            s = JSON.toJSONString(jgLhjgCreditAssessEntity);
            sysAuditService.saveSuccessAudit("通过id获取企业信用评估信息成功", Constant.ZFJG_DETAIL, Constant.PT, Constant.ZFJG_SELECT, s, request);
            return R.ok().put("data", jgLhjgCreditAssessEntity);
        } catch (Exception e) {
            e.printStackTrace();
            sysAuditService.saveFailAudit("通过id获取企业信用评估信息失败", Constant.ZFJG_DETAIL, Constant.YZ, Constant.ZFJG_SELECT, s, e, request);
            return R.error(e.getMessage());
        }
    }
    /**
     * 导出
     * 导出选中行数据，待定
     *
     * @param response
     * @param ids
     * @return
     */
    @GetMapping("/exportByIds2")
    public List exportCreditAssessToExcel(HttpServletResponse response, @RequestParam String ids) {
        List<Detail> creditAssessEntities = detailService.queryByIds(ids);
        return creditAssessEntities;
    }

    /**
     * 根据参数导出数据到Excel
     *
     * @param enterpriseName
     * @param enterpriseScoreBegin
     * @param enterpriseScoreEnd
     * @param enterpriseClassification
     * @return
     */
    @GetMapping("/export2")
    public List export(@RequestParam(required = false) String enterpriseName,
                       @RequestParam(required = false) String enterpriseScoreBegin,
                       @RequestParam(required = false) String enterpriseScoreEnd,
                       @RequestParam(required = false) String enterpriseClassification) {
        List<Detail> jgLhjgCreditAssessEntities = detailService.queryByParams(enterpriseName, enterpriseScoreBegin,
                enterpriseScoreEnd,enterpriseClassification);
        return jgLhjgCreditAssessEntities;
    }


    /**
     * 判断Excel表格中是否存在企业证件号码相同企业名称不同的数据
     *
     * @param file
     * @return
     */
    @PostMapping("/checkName")
    public R checkName(@RequestParam("file") MultipartFile file) {
        String s = "";
        try {
            R r = detailService.checkName(file);
            if("500".equals(r.get("code"))) {
                return R.error((String)r.get("msg"));
            }
            boolean isExist = (boolean) r.get("isExist");
            String existMessage = (String) r.get("existMessage");
            return R.ok().put("isExist", isExist).put("existMessage", existMessage);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error(e.getMessage());
        }
    }


    /**
     * 模板下载
     */
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(){
        String s = "";
        try {
            String fileName = "信用评估结果明细模板.xlsx";
            platformFileUtil.download(fileName);
            s = JSON.toJSONString(fileName);
            sysAuditService.saveSuccessAudit("信用评估结果明细模板下载成功", Constant.ZFJG_PENALTY, Constant.PT, Constant.ZFJG_DOWNLOADTEMPLATE, s, request);
        }catch (Exception e){
            sysAuditService.saveFailAudit("信用评估结果明细模板下载失败", Constant.ZFJG_PENALTY, Constant.YZ, Constant.ZFJG_DOWNLOADTEMPLATE, s, e, request);
        }
    }


    /**
     * 联合监管获取监管对象信息
     * @param pageSize
     * @param pageNo
     * @return
     */
    @GetMapping("/creditInfos")
    public R getCreditInfos(@RequestParam Integer pageSize, @RequestParam Integer pageNo) {
        try {
            PageRequest pageRequest = PageRequest.of(pageNo - 1, pageSize);
            QueryResults<Detail> detailQueryResults = detailService.getCreditInfos(pageRequest);
            return R.ok().put("data", detailQueryResults);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

}
